<!-- 到仓预约 -->
<template>
  <div class='appointment'>
    <van-nav-bar title="到仓预约" safe-area-inset-top />
    <van-form @submit="onSubmit" class="vanForm">

      <van-field readonly v-model="formData.warehouseName" name="warehouseName" label="预约仓库"/>

      <van-field v-model="formData.driverName" name="driverName" label="司机名称" placeholder="司机名称"
        :rules="[{ required: true, message: '请填写司机名称' }]" />

      <van-field v-model="formData.vehicleNo" name="vehicleNo" label="车牌号码" placeholder="车牌号码"
        :rules="[{ required: true, message: '请填写车牌号码' }]" />

      <van-field v-model="formData.driverPhone" name="driverPhone" label="司机电话" placeholder="司机电话"
        :rules="[{ required: true, message: '请填写司机电话' }]">
        <template #button>
          <van-button size="small" type="primary" :disabled="disabled" native-type="button" @click="handleSend">{{ text }}</van-button>
        </template>
      </van-field>
      <van-field v-model="formData.smsCode" name="smsCode" label="验证码" placeholder="验证码"
        :rules="[{ required: true, message: '请填写验证码' }]" />

      <van-field readonly clickable v-model="formData.name" name="预约送货客户" label="预约送货客户" placeholder="选择预约送货客户"
        :rules="[{ required: true, message: '请选择预约送货客户' }]"
        @click="showPickerFn(['agentId', 'companyName','customerCode','customerId','customerName','name'], customerList)" />

      <van-field name="预约入库订单" label="预约入库订单" placeholder="选择预约入库订单" :rules="[{ required: true, message: '请选择预约入库订单' }]">
        <template #input>
          <van-checkbox-group class="checkbox-group" @change="checkboxChange" v-model="formData.omsInboundScheduleDetailList" direction="horizontal">
            <van-checkbox class="checkbox" v-for="(item,index) in ordeList" :key="index" :name="item" shape="square">{{ item.receivingOrderCode }}</van-checkbox>
          </van-checkbox-group>
        </template>
      </van-field>

      <van-field v-model="formData.transitNo" name="transitNo" label="运单编号" placeholder="运单编号"
        :rules="[{ required: true, message: '请填写运单编号' }]" />

      <van-field readonly v-model="formData.expectPackagingQty" name="expectPackagingQty" label="申报包数" placeholder="申报包数"/>

      <van-field readonly v-model="formData.expectBoxQty" name="expectBoxQty" label="申报箱数" placeholder="申报箱数"/>

      <van-field readonly v-model="formData.weight" name="weight" label="货物总重量"  placeholder="货物总重量"/>
      <van-field readonly v-model="formData.volumn" name="volumn" label="货物总体积" placeholder="货物总体积" />

      <van-field readonly clickable v-model="formData.expectedDate" name="expectedDate" label="预约到仓时间"
        placeholder="选择预约到仓时间" :rules="[{ required: true, message: '请选择预约到仓时间' }]" @click="showCalendar = true" />

      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">提交</van-button>
      </div>
    </van-form>

    <!-- 日期选择 -->
    <van-calendar v-model="showCalendar" @confirm="calendarConfirm" />

    <!-- 下拉选择 -->
    <van-popup v-model="showPicker" position="bottom">
      <van-picker show-toolbar value-key="label" :columns="columns" @confirm="pickerConfirm"
        @cancel="showPicker = false" />
    </van-popup>
  </div>
</template>
<script>
export default {
  data () {
    return {
      disabled: false,
      text: '发送验证码',
      formData: {
        name: '',
        warehouseId: '',
        warehouseName: '',
        warehouseCode: '',
        smsCode: '',
        driverName: '',
        driverPhone: '',
        transitNo: '',
        vehicleNo: '',
        omsInboundScheduleDetailList: [],
        expectPackagingQty: '',
        weight: '',
        volumn: '',
        expectedDatetime: '',
        expectedDate: '',
        customerName: '',
        customerId: '',
        customerCode: '',
        companyName: '',
        agentId: ''
      },
      showCalendar: false,
      columns: [],
      customerList: [],
      ordeList: [],
      showPicker: false,
      // 打开选择器时 值赋给formData中对应的key
      keyPicker: []
    }
  },
  mounted () {
    if (this.$route.query.warehouseId) {
      this.getWarehouseName()
    } else {
      this.$toast.fail('未获取到仓库信息，请检查！')
    }
  },
  methods: {
    getWarehouseName(){
      this.$ajax({
        url: '/oms-api/client/OmsInboundScheduleClientRpc/selectWarehouseById.json',
        data: {
          warehouseId: this.$route.query.warehouseId
        },
        success: res => {
          if(res&&res.data){
            Object.assign(this.formData,res.data)
            this.getByWarehouse()
          }
        }
      })
    },
    // 发送验证码
    handleSend () {
      if (!this.formData.driverPhone) {
        this.$toast.fail('请填写司机电话')
        return
      }
      this.$ajax({
        url: '/oms-api/client/OmsInboundScheduleClientRpc/sendScheduleSmsCode.json',
        data: {
          driverPhone: this.formData.driverPhone
        },
        success: () => {
          this.$toast.success('发送成功')
          this.afterSend()
        }
      })
    },
    afterSend () {
      if (this.disabled) return
      this.disabled = true
      let n = 60
      this.text = `剩余 ${n} s`
      const run = setInterval(() => {
        n = n - 1
        this.text = `剩余 ${n} s`

        if (n < 0) {
          clearInterval(run)
          this.disabled = false
          this.text = '重新发送'
        }
      }, 1000)
    },
    // 获取客户列表
    getByWarehouse () {
      this.$ajax({
        url: '/oms-api/client/OmsBaseWarehouseClientRpc/getByWarehouseId.json',
        data: {
          warehouseId: this.$route.query.warehouseId
        },
        success: ({ data }) => {
          this.customerList = data.rows.map(item => {
            return {
              ...item,
              label: item.name
            }
          })
        }
        // fail: () => {
        //   setTimeout(() => {
        //     this.$router.back()
        //   }, 3000)
        // }
      })
    },
    // 获取入库订单信息
    getOrde () {
      this.$toast.loading({
        duration: 0,
        forbidClick: true,
        message: '加载中...'
      })
      this.$ajax({
        url: '/oms-api/client/OmsInboundScheduleClientRpc/selectByWarehouseIdAndCustomerId.json',
        data: {
          warehouseId: this.$route.query.warehouseId,
          customerId: this.formData.customerId
        },
        success: ({ data }) => {
          // 手动清除 Toast
          this.$toast.clear()

          this.ordeList = data.rows.map(item => {
            return {
              ...item,
              label: item.receivingOrderCode
            }
          })
        },
        fail: () => {
          // 手动清除 Toast
          this.$toast.clear()
        }
      })
    },
    // 日期选择
    calendarConfirm (date) {
      this.formData.expectedDate = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
      this.showCalendar = false
    },
    // 下拉选择
    showPickerFn (keys, columns) {
      // 赋值对象
      this.keyPicker = keys
      // 选择器内容
      this.columns = columns
      this.showPicker = true
    },
    pickerConfirm (value) {
      if (typeof value === 'object') {
        this.keyPicker.forEach(key => {
          this.formData[key] = value[key]
        })

        // 获取入库订单
        if (value.customerId) {
          this.formData.omsInboundScheduleDetailList = []
          this.getOrde()
        }
      } else {
        this.formData[this.keyPicker[0]] = value
      }
      this.showPicker = false
    },
    checkboxChange () {
      this.formData.expectPackagingQty = 0
      this.formData.expectBoxQty = 0
      this.formData.weight = 0
      this.formData.volumn = 0

      this.formData.omsInboundScheduleDetailList.forEach((item, index) => {
        this.formData.expectPackagingQty += item.expectPackagingQty
        this.formData.expectBoxQty += item.expectBoxQty
        this.formData.weight += item.totalWeight
        this.formData.volumn += item.totalVolume
      })

      this.formData.weight = this.formData.weight.toString().match(/^\d+(?:\.\d{0,2})?/)[0]
      this.formData.volumn = this.formData.volumn.toString().match(/^\d+(?:\.\d{0,2})?/)[0]
    },
    onSubmit () {
      const toast = this.$toast.loading({
        duration: 0,
        forbidClick: true,
        message: '加载中...'
      })
      this.$ajax({
        url: '/oms-api/client/OmsInboundScheduleClientRpc/saveH5.json',
        type: 'json',
        data: {
          ...this.formData,
          omsInboundScheduleDetailList:this.formData.omsInboundScheduleDetailList.map(item=>{
            return {
              ...item,
              weight:item.totalWeight,
              volumn:item.totalVolume,
            }
          }),
          expectedDatetime: (new Date(this.formData.expectedDate + ' 00:00:00')).getTime(),
          expectedDate: (new Date(this.formData.expectedDate)).getTime()
        },
        success: () => {
          toast.clear()
          this.$toast.success({
            message: `您提交的预约已成功申请，请按照您预约的时间将货物送到【${this.formData.warehouseName}】仓库`,
            duration: 5000
          })
        },
        fail: (e) => {
          toast.clear()
          this.$toast.fail({
            message: e.message,
            duration: 5000
          })
        }
      })
    }
  }
}
</script>

<style scoped lan="scss">
.appointment {
  width: 100%;
  height: 100vh;
  overflow: auto;
  font-size: 24px;
}

.vanForm {
  margin-top: 24px;
}

.checkbox-group{
  max-height: 300px;
  overflow: auto;
}
.checkbox {
  width: 100%;
  margin-bottom: 10px;
}
</style>
